import { HttpException, Inject, Injectable, Module } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { WeChatService } from "nest-wechat";
import axios from "axios";
import * as FormData from "form-data";
import * as fs from "fs";
import * as fetch from "node-fetch";
import { getAccessToken } from "./wechat";

@Injectable()
export class COS {
  constructor(
    private readonly weChatService: WeChatService,
    private readonly configService: ConfigService
  ) {
  }

  async uploadFile(filePath: string, fileName: string) {
    try {
      const { url, authorization, token, cos_file_id } = await this.getUploadUrl(fileName);
      console.log(url);
      console.log(fileName);
      console.log(filePath);
      const formData = new FormData();
      formData.append("key", fileName);
      formData.append("Signature", authorization);
      formData.append("x-cos-security-token", token);
      formData.append("x-cos-meta-fileid", cos_file_id);
      formData.append("file", fs.createReadStream(filePath));

      const length = await this.promiseLength(formData);
      const resp = await fetch(url, {
        method: "POST",
        body: formData,
        headers: {
          "Content-Type": `multipart/form-data; boundary=${formData.getBoundary()}`,
          "Content-Length": `${length}`
        }
      });

      if (!resp.status) {
        throw new HttpException("Upload failed with status " + resp.status, 500);
      }
      return true;
    } catch (err) {
      console.log("上传文件失败 ====== ", err);
      throw err;
    }
  }

  async downloadFile(url: string, local_path: string) {
    try {
      const response = await fetch(url);
      const buffer = await response.buffer();
      fs.writeFileSync(local_path, buffer);
      return true;
    } catch (error) {
      console.error("Failed to download err:", error);
    }
    return false;
  }

  private promiseLength = (formData: FormData) => new Promise((resolve, reject) => formData.getLength((err, length) => (err ? reject(err) : resolve(length))));


  private async getUploadUrl(path: string) {
    console.log({
      env: this.configService.get("TENCENT_CLOUD_ENV"),
      path
    });
    const accessToken = await getAccessToken(this.weChatService.config.appId, this.weChatService.config.secret);
    const url = `http://api.weixin.qq.com/tcb/uploadfile?access_token=${accessToken.data.access_token}&type=image`;
    const response = await axios.post(url, {
      env: this.configService.get("TENCENT_CLOUD_ENV"),
      path
    });
    if (response.data.errcode === 0) {
      return response.data;
    }
    throw new HttpException(response.data.errmsg, 500);
  }
}
